﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ShoppingListEntities;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.IO;
using System.Linq;
using Microsoft.Phone;
namespace ShoppingList.Helpers
{
    public static class DataBaseHelpers
    {
        public static readonly string Cnn = "isostore:/shoppinglistdb.sdf";

        public static bool VerifyExistDataBase()
        {
            using (ShoppingListDataContext dataContext = new ShoppingListDataContext(Cnn))
            {
                //        dataContext.DeleteDatabase();

                //if (dataContext.DatabaseExists())
                //{
                //    dataContext.DeleteDatabase();
                //}
                return dataContext.DatabaseExists();
            }
        }


        public static void SetupDataBase()
        {
            using (ShoppingListDataContext dataContext = new ShoppingListDataContext(Cnn))
            {
                //        dataContext.DeleteDatabase();

                //if (dataContext.DatabaseExists())
                //{
                //    dataContext.DeleteDatabase();
                //}
                if (dataContext.DatabaseExists() == false)
                {
                    //dataContext.CreateDatabase();
                    RestoreDataBase();
                }
            }
        }

        private static void RestoreDataBase()
        {
            try
            {
                
              Stream db = Application.GetResourceStream(new Uri(@"/ShoppingList;component/DataInfo/shoppinglistdb.sdf", UriKind.Relative)).Stream;

             
                 
                    byte[] buffer = new byte[db.Length];

                    db.Read(buffer, 0, (int)db.Length);

                    IsolatedStorageFile isostore = IsolatedStorageFile.GetUserStoreForApplication();
                    using (IsolatedStorageFileStream workdb = isostore.CreateFile("shoppinglistdb.sdf"))
                    {
                        workdb.Write(buffer, 0, buffer.Length);
                        workdb.Flush();
                    }
                    db.Close();
                    db.Dispose();
                

                    SaveLocalImage("06a797af-607f-404a-a5ed-ef1f88fc6acd.jpg", "Images");
                    SaveLocalImage("1626f45f-7387-4174-8a4e-539da8e21ca6.jpg", "Images");
                    SaveLocalImage("1aa757f6-66de-4981-8d28-a09ffeef44c2.jpg", "Images");
                    SaveLocalImage("1aaed873-39ae-4c8e-a2e8-cbfa4dbb3f0a.jpg", "Images");
                    SaveLocalImage("1d421788-0b7e-4bc2-ba24-35616add362d.jpg", "Images");

                    SaveLocalImage("1e9144c4-91cd-4b62-88c7-d48abf50a37f.jpg", "Images");
                    SaveLocalImage("2d87ce60-25d6-4931-9cad-96749ac8e181.jpg", "Images");
                    SaveLocalImage("33c6159a-ca89-4bbe-a92a-e10ca27c8f00.jpg", "Images");
                    SaveLocalImage("47750ad2-37a7-4998-87f3-8031764784d6.jpg", "Images");
                    SaveLocalImage("4b09f506-5905-4724-9563-d36a4c510786.jpg", "Images");

                    SaveLocalImage("550dd274-fada-4b0a-8abf-bd2e7f331c88.jpg", "Images");
                    SaveLocalImage("638193e7-502d-4185-bd17-d56f5efb3525.jpg", "Images");
                    SaveLocalImage("72974ff5-30d5-4e38-a78d-0bc54f49cc20.jpg", "Images");
                    SaveLocalImage("836fbf00-fd0e-4d17-b66e-ea01ff79e5ca.jpg", "Images");
                    SaveLocalImage("cf76d987-c167-4e20-b415-18679ed3fba1.jpg", "Images");


                    SaveLocalImage("e022ed89-83f9-43f5-8f69-dc93f5509a2e.jpg", "Images");
                    SaveLocalImage("e5849cfc-5d8c-4919-9e98-8649397fc795.jpg", "Images");
                    SaveLocalImage("e9db22d9-45c8-4485-88b0-e05a757ae5d2.jpg", "Images");
                    SaveLocalImage("ea88e16d-a880-49b0-807c-0d0bfda216e0.jpg", "Images");
            }
            catch(Exception ex)
            {
                using (ShoppingListDataContext dataContext = new ShoppingListDataContext(Cnn))
                {
                    //        dataContext.DeleteDatabase();

                    //if (dataContext.DatabaseExists())
                    //{
                    //    dataContext.DeleteDatabase();
                    //}
                    if (dataContext.DatabaseExists() == false)
                    {
                        dataContext.CreateDatabase();

                    }
                }
            }
           
        }

        private static void SaveLocalImage(string Name,string Folder)
        {
            string tempJPG = System.IO.Path.Combine("/" + Folder + "/", Name);
            string pathimage = System.IO.Path.Combine(@"/ShoppingList;component/DataInfo/", Name);
            BitmapImage bitmap = null ;
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                if (!myIsolatedStorage.DirectoryExists("Images"))
                {
                    myIsolatedStorage.CreateDirectory("Images");
                }
                if (myIsolatedStorage.FileExists(tempJPG))
                {
                    myIsolatedStorage.DeleteFile(tempJPG);
                }
                myIsolatedStorage.Dispose();
            }

            using (var filestream = new IsolatedStorageFileStream(tempJPG, FileMode.CreateNew, IsolatedStorageFile.GetUserStoreForApplication()))
            {

                Stream db = Application.GetResourceStream(new Uri(pathimage, UriKind.Relative)).Stream;


              
                 
                
                
             
                Helpers.DispatchService.Dispatch(() =>
                {
                    WriteableBitmap wb = PictureDecoder.DecodeJpeg(db);
                    wb.SaveJpeg(filestream,wb.PixelWidth, wb.PixelHeight, 0, 100);


                    StreamResourceInfo sri = null;
                    Uri uri = new Uri(tempJPG, UriKind.Relative);
                    sri = Application.GetResourceStream(uri);

                    filestream.Close();

                    filestream.Dispose();
                });

                db.Close();
                db.Dispose();

            }  



        }

        public static string SaveImage(BitmapImage Img)
        {
           
            if(Img!=null)
            {

            WriteableBitmap writeablebitmap;
            string tempJPG = @"\Images\" + Guid.NewGuid().ToString() + ".jpg";
            writeablebitmap = new WriteableBitmap(Img);


            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                        if (!myIsolatedStorage.DirectoryExists("Images"))
                        {
                            myIsolatedStorage.CreateDirectory("Images");
                        }
                        if (myIsolatedStorage.FileExists(tempJPG))
                        {
                            myIsolatedStorage.DeleteFile(tempJPG);
                        }
                        myIsolatedStorage.Dispose();
            }

                        using (var filestream = new IsolatedStorageFileStream(tempJPG, FileMode.CreateNew, IsolatedStorageFile.GetUserStoreForApplication()))  
                    {
                       // BitmapImage bitmap = new BitmapImage();
                        Helpers.DispatchService.Dispatch(() => { 
                        WriteableBitmap wb = new WriteableBitmap(Img);
                        wb.SaveJpeg(filestream, 250, 250, 0, 90);


                        StreamResourceInfo sri = null;
                        Uri uri = new Uri(tempJPG, UriKind.Relative);
                        sri = Application.GetResourceStream(uri);
                     
                        filestream.Close();

                        filestream.Dispose();
                        });

                        return tempJPG;
                 
                    }  


               
               

                //StreamResourceInfo sri = null;
                //Uri uri = new Uri(tempJPG, UriKind.Relative);
                //sri = Application.GetResourceStream(uri);
                //writeablebitmap.SaveJpeg(fileStream, 250, 250, 0, 90);
                //fileStream.Close();
                //fileStream.Dispose();
                



            }

            

            return "WithOut Image";
        }

        public static BitmapImage LoadImage(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {


                BitmapImage bi = new BitmapImage();
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) 
                {
                    try
                    {
                        using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(path.Trim(), FileMode.Open, FileAccess.Read))
                        {
                            if (fileStream.Length > 0)
                            {
                                bi.SetSource(fileStream);
                                return bi;
                            }
                            else
                            {
                                return null;
                            }
                           
                        }
                    }
                    catch (IsolatedStorageException ex)
                    {
                        return null;
                    }
                    finally
                    {
                        myIsolatedStorage.Dispose();
                    }
                   
                }

                  
            }

            return null;
        }

        public static void DeleteImage(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                

                BitmapImage bi = new BitmapImage();

                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    try
                    {
                        if (myIsolatedStorage.FileExists(path))
                        {
                            myIsolatedStorage.DeleteFile(path);
                        }
                        
                    }
                    catch(IsolatedStorageException ex)
                    {

                    }
                  

                }
            }
        }

        public static int getTotalOfProducts()
        {
            using (ShoppingListDataContext dataContext = new ShoppingListDataContext(Cnn))
            {
                //        dataContext.DeleteDatabase();
                if (dataContext.DatabaseExists())
                {

                    return dataContext.Products.Count();

                }

                return 0;
            }
        }
    }
}
